export default class WebsocketTask {
    constructor(url) {
      this.url = url;
      this.socketTask = null;
      this.connect();
    }
    
    connect() {
      this.socketTask = uni.connectSocket({
        url: this.url,
        header:{
            'content-type': 'application/json'
        }
      });
     
      uni.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开！');
      });
      
      this.socketTask.onMessage((res) => {
        console.log('收到服务器消息:', res.data);
      });
      
      this.socketTask.onClose(() => {
        console.log('WebSocket连接已关闭');
      });
      
      this.socketTask.onError((err) => {
        console.error('WebSocket连接发生错误:', err);
      });
    }
    
    send(data) {
      if (this.socketTask) {
        this.socketTask.send({
          data: data,
        });
      }
    }
    
    close() {
      if (this.socketTask) {
        this.socketTask.close();
      }
    }
  }